package com.ruoyi.framework.manager.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.TimerTask;
import java.util.UUID;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysDictType;
import com.ruoyi.framework.config.ApplicationContextHolder;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.AllCustomsCodesMapper;
import com.ruoyi.system.service.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.LogUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 异步工厂（产生任务用）
 * 
 * @author ruoyi
 */
public class AsyncFactory
{

//    @Resource
//    private static AllCustomsCodesMapper allCustomsCodesMapper;
//    @Resource
//    private IAllCustomsCodesService allCustomsCodesService;


    private static final Logger sys_user_logger = LoggerFactory.getLogger("sys-user");

    /**
     * 记录登录信息
     * 
     * @param username 用户名
     * @param status 状态
     * @param message 消息
     * @param args 列表
     * @return 任务task
     */
    public static TimerTask recordLogininfor(final String username, final String status, final String message,
            final Object... args)
    {
        final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        final String ip = IpUtils.getIpAddr();
        return new TimerTask()
        {
            @Override
            public void run()
            {
                String address = AddressUtils.getRealAddressByIP(ip);
                StringBuilder s = new StringBuilder();
                s.append(LogUtils.getBlock(ip));
                s.append(address);
                s.append(LogUtils.getBlock(username));
                s.append(LogUtils.getBlock(status));
                s.append(LogUtils.getBlock(message));
                // 打印信息到日志
                sys_user_logger.info(s.toString(), args);
                // 获取客户端操作系统
                String os = userAgent.getOperatingSystem().getName();
                // 获取客户端浏览器
                String browser = userAgent.getBrowser().getName();
                // 封装对象
                SysLogininfor logininfor = new SysLogininfor();
                logininfor.setUserName(username);
                logininfor.setIpaddr(ip);
                logininfor.setLoginLocation(address);
                logininfor.setBrowser(browser);
                logininfor.setOs(os);
                logininfor.setMsg(message);
                // 日志状态
                if (StringUtils.equalsAny(status, Constants.LOGIN_SUCCESS, Constants.LOGOUT, Constants.REGISTER))
                {
                    logininfor.setStatus(Constants.SUCCESS);
                }
                else if (Constants.LOGIN_FAIL.equals(status))
                {
                    logininfor.setStatus(Constants.FAIL);
                }
                // 插入数据
                SpringUtils.getBean(ISysLogininforService.class).insertLogininfor(logininfor);
            }
        };
    }

    /**
     * 操作日志记录
     * 
     * @param operLog 操作日志信息
     * @return 任务task
     */
    public static TimerTask recordOper(final SysOperLog operLog)
    {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                // 远程查询操作地点
                operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
                SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);
            }
        };
    }



    public static TimerTask importExcelDataAll(final InputStream inputStream,final String type) throws Exception {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                // 远程查询操作地点
                Workbook workbook = null;
                try {
                    workbook = new XSSFWorkbook(inputStream);
                    SysDictType dictType = ApplicationContextHolder.getBean(ISysDictTypeService.class).selectDictTypeById(11L);
                    dictType.setStatus("0");
                    ApplicationContextHolder.getBean(ISysDictTypeService.class).updateDictType(dictType);
                    Sheet sheet = workbook.getSheetAt(0);  // 获取第一个工作表
                    // 清空表
                    if (type != null && !type.isEmpty() && type.equals("1")){
                        ApplicationContextHolder.getBean(IDataMatchingService.class).deleteDataMatchingData();
                    }
                    for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                        SysDictType sysDictType = ApplicationContextHolder.getBean(ISysDictTypeService.class).selectDictTypeById(11L);
                        if (sysDictType == null && sysDictType.getStatus().equals("1")) {
                            ApplicationContextHolder.getBean(IDataMatchingService.class).deleteDataMatchingData();
                            break;
                        }
                        Row row = sheet.getRow(i);
                        if (getCellValue(row, 0).isEmpty() && getCellValue(row, 1).isEmpty() && getCellValue(row, 2).isEmpty() && getCellValue(row, 3).isEmpty() && getCellValue(row, 4).isEmpty() && getCellValue(row, 5).isEmpty() && getCellValue(row, 6).isEmpty()) {
                            continue;
                        }
                        DataMatching commodityInfo = new DataMatching();
                        String id = UUID.randomUUID().toString().replace("-", "");
                        commodityInfo.setId(id);
                        commodityInfo.setEori(getCellValue(row, 0));
                        commodityInfo.setClientsDescription(getCellValue(row, 1));
                        commodityInfo.setClientsDescriptionInChinese(getCellValue(row, 2));
                        commodityInfo.setMaterial(getCellValue(row, 3));
                        commodityInfo.setClientsHsCode(getCellValue(row, 4));
                        commodityInfo.setAsin(getCellValue(row, 5));
                        commodityInfo.setCommodity(getCellValue(row, 6));
                        commodityInfo.setHsCode(getCellValue(row, 7));
                        commodityInfo.setThirdCountryDuty(getCellValue(row, 8));

                        if (commodityInfo.getEori().isEmpty() && commodityInfo.getClientsDescription().isEmpty() && commodityInfo.getClientsDescriptionInChinese().isEmpty() && commodityInfo.getMaterial().isEmpty() && commodityInfo.getClientsHsCode().isEmpty() && commodityInfo.getAsin().isEmpty()) {
                            continue;
                        }
                        if (type!=null && type.equals("1")){
                            ApplicationContextHolder.getBean(IDataMatchingService.class).insertDataMatchingLs(commodityInfo);
                        } else {
                            ApplicationContextHolder.getBean(IDataMatchingService.class).insertDataMatching(commodityInfo);
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }finally {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        };
    }

    private static String getCellValue(Row row, int colIndex) {
        Cell cell = row.getCell(colIndex);
        if (cell != null) {
            return cell.toString();
        }
        return "";
    }

    public static TimerTask importExcelDataSj(final InputStream inputStream, final String type) throws Exception {

        return new TimerTask()
        {
            @Override
            public void run()
            {
                // 远程查询操作地点
                Workbook workbook = null;
                try {
                    workbook = new XSSFWorkbook(inputStream);
                    Sheet sheet = workbook.getSheetAt(0);  // 获取第一个工作表
                    JSONObject res = new JSONObject();
                    int resNum=0;
                    int errorNum=0;
                    // 从第二行开始读取数据（第一行是表头）
                    for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {

                        Row row = sheet.getRow(i);
                        if (getCellValue(row, 0).isEmpty() && getCellValue(row, 1).isEmpty() && getCellValue(row, 2).isEmpty() && getCellValue(row, 3).isEmpty() && getCellValue(row, 4).isEmpty() && getCellValue(row, 5).isEmpty() && getCellValue(row, 6).isEmpty()) {
                            continue;
                        }
                        AllCustomsCodes commodityInfo = new AllCustomsCodes();
                        String id = UUID.randomUUID().toString().replace("-", "");
                        commodityInfo.setId(id);
                        commodityInfo.setCommodityCode(getCellValue(row, 0));
                        commodityInfo.setThirdCountryDuty(getCellValue(row, 1));
                        commodityInfo.setClassification(getCellValue(row, 2));
                        commodityInfo.setSection(getCellValue(row, 3));
                        commodityInfo.setSectionTitle(getCellValue(row, 4));
                        commodityInfo.setChapters(getCellValue(row, 5));
                        commodityInfo.setStatus(getCellValue(row, 6));
                        commodityInfo.setType(type);
                        ApplicationContextHolder.getBean(IAllCustomsCodesService.class).insertAllCustomsCodes(commodityInfo);
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }finally {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        };
    }


    public static TimerTask importExcelDataFqx(InputStream inputStream) {
        return new TimerTask()
        {
            @Override
            public void run()
            {
                // 远程查询操作地点
                Workbook workbook = null;
                try {
                    workbook = new XSSFWorkbook(inputStream);
                    Sheet sheet = workbook.getSheetAt(0);  // 获取第一个工作表
                    int rowCount = sheet.getPhysicalNumberOfRows();  // 获取总行数

                    for (int i = 1; i < rowCount; i++) {  // 跳过表头，开始读取数据
                        Row row = sheet.getRow(i);
                        if (row == null) continue;

                        AntiDumping commodityInfo = new AntiDumping();
                        String id = UUID.randomUUID().toString().replace("-", "");
                        commodityInfo.setId(id);

                        // 获取单元格数据，并确保将其作为字符串处理
                        String commodityCode = getCellValue(row, 0);  // 获取第一个单元格值（Commodity Code）
                        String remarks = getCellValue(row, 1);  // 获取第二个单元格值（Remarks）

                        commodityInfo.setCommodityCode(commodityCode);
                        commodityInfo.setRemarks(remarks);

                        try {
                            ApplicationContextHolder.getBean(IAntiDumpingService.class).insertAntiDumping(commodityInfo);
                        } catch (Exception e) {
                            System.err.println("插入数据失败，行号：" + i + " 错误信息：" + e.getMessage());
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }finally {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        };
    }
}
